#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QPainterPath>
#include <QMenu>
#include "./tools/logic/clientmessagehandler.h"
#include "./tools/ui/paintshadow.h"
#include "./tools/ui/draghandler.h"
#include "./tools/database/dbservice.h"
#include "./tools/utils/networkmanager.h"
#include "./widgets/mainWindow/subWidgets/chatView/chatbox.h"
#include <QSplitter>

MainWindow::MainWindow(const QString userId, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWindow), m_userId(userId)
{
    ui->setupUi(this);

    initUI();
    initTray();
    initThreadSignalsAndSlots();
    // 触发一下分割条来初始化
    emit ui->mainWindowSplitter->splitterMoved(0,0);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initUI()
{
    /* 初始化主窗口属性 */
    // 移除标题栏和边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    // 设置窗口为透明，要不然阴影绘制没效果
    this->setAttribute(Qt::WA_TranslucentBackground);
    // 安装事件过滤器让鼠标在任意位置拖动窗口
    DragHandler *dragHandler = new DragHandler(this);
    installEventFilter(dragHandler);

    /* 初始化主窗口各个控件 */
    // 填充用户id
    ui->labelUserId->setText(m_userId);
    // 左边一列按钮宽度
    int sideLength = 40;
    // 左边距
    int xOffset = 30;
    // 上边距
    int yOffset = 90;
    // 按钮垂直间隔
    int y_step = 60;
    // 设置左窗口大小位置
    int leftWidgetX = 2 * xOffset - m_shadowWidth + sideLength;
    int leftWidgetY = m_shadowWidth;
    int leftWidgetW = 220;
    int leftWidgetHeight = this->height() - m_shadowWidth * 2;
    // ui->leftWidget->setGeometry(QRect(leftWidgetX, leftWidgetY, leftWidgetW, leftWidgetHeight));
    int mainWindowSplitterX = 2 * xOffset - m_shadowWidth + sideLength;
    int mainWindowSplitterY = m_shadowWidth;
    int mainWindowSplitterWidth = this->width() - mainWindowSplitterX - m_shadowWidth;
    int mainWindowSplitterHeight = this->height() - m_shadowWidth * 2;
    ui->mainWindowSplitter->setGeometry(
        QRect(mainWindowSplitterX, mainWindowSplitterY, mainWindowSplitterWidth, mainWindowSplitterHeight));
    ui->mainWindowSplitter->setHandleWidth(1);
    ui->leftWidget->setMinimumWidth(150);
    ui->rightWidget->setMinimumWidth(300);
    QList<int> sizes;
    sizes << 300 << 600;
    ui->mainWindowSplitter->setSizes(sizes);
    connect(ui->mainWindowSplitter, &QSplitter::splitterMoved, [=](int pos, int index) {
        if (m_contactListWidget)
        {
            m_contactListWidget->setGeometry(QRect(0, 0, ui->leftWidget->width(), ui->leftWidget->height()));
        }
        if (m_chatWidget)
        {
            m_chatWidget->setGeometry(QRect(0, 0, ui->rightWidget->width(), ui->rightWidget->height()));
        }
    });

    // 设置聊天按钮大小位置
    ui->btnChatView->setGeometry(QRect(xOffset, yOffset, sideLength, sideLength));
    // 设置添加好友按钮大小位置
    ui->btnAddFriendView->setGeometry(QRect(xOffset, yOffset + 1*y_step, sideLength, sideLength));
    // 设置新好友申请按钮大小位置
    ui->btnNewFriendView->setGeometry(QRect(xOffset, yOffset + 2*y_step, sideLength, sideLength));
    // 设置登出按钮大小位置
    int btnLogoutY = this->height() - sideLength - xOffset;
    ui->btnLogOut->setGeometry(QRect(xOffset, btnLogoutY, sideLength, sideLength));

    // 设置右上角三个控制窗口按钮
    ui->btnSetMin->raise();  // 提升到最前
    ui->btnSetMax->raise();
    ui->btnClose->raise();
    connect(ui->btnSetMin, &QPushButton::clicked, this, &MainWindow::onBtnSetMinClicked);
    connect(ui->btnSetMax, &QPushButton::clicked, this, &MainWindow::onBtnSetMaxClicked);
    connect(ui->btnClose, &QPushButton::clicked, this, &MainWindow::onBtnCloseClicked);


    /* 初始化 好友聊天视图（视图1） 中的控件 */
    m_contactListWidget = new ContactListWidget(ui->leftWidget);
    m_contactListWidget->hide();
    m_contactListWidget->setGeometry(QRect(0, 0, ui->leftWidget->width(), ui->leftWidget->height()));
    connect(m_contactListWidget->getListContact(), &QListWidget::itemClicked, this, &MainWindow::onContactListItemClicked);

    m_chatWidget = new ChatWidget(ui->rightWidget);
    m_chatWidget->hide();
    m_curContact = nullptr;
    connect(m_chatWidget->getVideoCallBtn(), &QPushButton::clicked, this, &MainWindow::onBtnVideoCallclicked);


    /* 初始化 添加、申请好友视图（视图2） 中的控件 */

    // 初始化leftWidget中可能会显示的添加好友窗口
    m_addFriendWidget = new AddFriendWidget(ui->leftWidget);
    m_addFriendWidget->getResultWidget()->hide();
    m_addFriendWidget->setGeometry(QRect(0, 0, ui->leftWidget->width(), ui->leftWidget->height()));

    // 初始化rightWidget中可能会显示的内容
    m_applyFriendWidget = new ApplyFriendWidget(ui->rightWidget);
    m_applyFriendWidget->hide();
    m_applyFriendWidget->setGeometry(QRect(0, 0, ui->rightWidget->width(), ui->rightWidget->height()));



    /* 初始化 展示好友申请视图（视图3） 中的控件 */
    m_newFriendList = new QListWidget(ui->leftWidget);
    m_newFriendList->hide();
    m_newFriendList->setGeometry(QRect(0, 0, ui->leftWidget->width(), ui->leftWidget->height()));
    // m_newFriendList->setStyleSheet(
    //     "background-color: transparent;" // 设置背景透明
    //     "border: none;"                  // 可选：去除边框
    //     );
    // 测试代码
    // QListWidgetItem* item = new QListWidgetItem;
    // item->setSizeHint(QSize(200,80));   // 这行一定要写，不然无法渲染
    // NewFriendWidget* newFriend = new NewFriendWidget("applicantId", "nickname", "verifyInfo", QDateTime());
    // m_newFriendList->addItem(item);
    // m_newFriendList->setItemWidget(item, newFriend);


    m_showFriendApplicationWidget = new ShowFriendApplicationWidget(ui->rightWidget);
    m_showFriendApplicationWidget->hide();
    m_showFriendApplicationWidget->setGeometry(QRect(0, 0, ui->rightWidget->width(), ui->rightWidget->height()));





    /* 绑定左侧一列按钮信号 */
    connect(ui->btnChatView, &QPushButton::clicked, this, &MainWindow::onBtnShowChatViewClicked);
    connect(ui->btnAddFriendView, &QPushButton::clicked, this, &MainWindow::onBtnShowAddFriendViewClicked);
    connect(ui->btnNewFriendView, &QPushButton::clicked, this, &MainWindow::onBtnShowFriendApplicationsViewBtnClicked);

    // 绑定登出按钮信号
    connect(ui->btnLogOut, &QPushButton::clicked, this, &MainWindow::onBtnLogoutClicked);


    /* 绑定 好友聊天视图（视图1） 中的按钮信号 */

    // 点击发送消息按钮
    connect(m_chatWidget->getSendMsgBtn(), &QPushButton::clicked, this, &MainWindow::onBtnSendMsgClicked);



    /* 绑定 添加、申请好友视图（视图2） 中的按钮信号 */

    // 点击搜索按钮发信号
    connect(m_addFriendWidget->getSearchBtn(), &QPushButton::clicked, this, &MainWindow::onSearchNewUserBtnClicked);
    // 点击申请好友按钮发信号
    connect(m_addFriendWidget->getCheckFriendInfoBtn(), &QPushButton::clicked, this, &MainWindow::onCheckFriendInfoBtnClicked);
    // 点击提交好友申请按钮
    connect(m_applyFriendWidget->getSubmitBtn(), &QPushButton::clicked, this, &MainWindow::onApplyFriendBtnClicked);


    /* 绑定 展示好友申请视图（视图3） 中的按钮信号 */


    connect(m_showFriendApplicationWidget->getAcceptBtn(), &QPushButton::clicked, this, &MainWindow::onAcceptedBtnClicked);
    connect(m_showFriendApplicationWidget->getRejectBtn(), &QPushButton::clicked, this, &MainWindow::onRejectedBtnClicked);

}

// 初始化系统托盘
void MainWindow::initTray()
{
    // 托盘图标
    m_trayIcon = new QSystemTrayIcon(this);
    m_trayIcon->setIcon(QIcon(":/images/chat.png")); // 设置托盘图标

    // 托盘菜单
    QMenu *trayMenu = new QMenu(this);
    QAction *restoreAction = new QAction("Open", this);
    connect(restoreAction, &QAction::triggered, this, &MainWindow::showNormal);
    trayMenu->addAction(restoreAction);

    QAction *quitAction = new QAction("Quit", this);
    connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
    trayMenu->addAction(quitAction);

    m_trayIcon->setContextMenu(trayMenu);
    m_trayIcon->show();

    // 双击托盘图标恢复窗口
    connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::onTrayIconActivated);
}

// 初始化线程间信号和槽
void MainWindow::initThreadSignalsAndSlots()
{
    /* UI线程（mainWindow）和Handler间通信 */

    // 发送搜索用户数据给Handler打包
    connect(this, &MainWindow::sendSearchNewUserInfo, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendSearchNewUserRequestMessage);
    // 接受搜索用户结果
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getSearchUserResponse,
            this, &MainWindow::dealSearchUserResponseMessage);

    // 发送登出请求
    connect(this, &MainWindow::sendLogoutInfo, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendLogoutRequestMessage);
    // 接受Handler解析好的登出结果数据
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getLogoutResponse,
            this, &MainWindow::dealLogoutResponseMessage);

    // 发送申请好友用户给Handler打包
    connect(this, &MainWindow::sendApplyFriendInfo, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendApplyFriendRequestMessage);
    // 接受好友申请消息
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getApplyFriendRequestToClient,
            this, &MainWindow::dealApplyFriendRequestMessageToClient);

    // UI发信号告诉Handler发送好友审核消息
    connect(this, &MainWindow::sendNewFriendStatus, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendApplyFriendResponseMessage);

    // 接受来自其他用户的好友审核结果
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getApplyFriendResponseToClient,
            this, &MainWindow::dealNewFriendApplicationResult);

    // 发送消息给好友
    connect(this, &MainWindow::sendNewMessage, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendChatMessage);

    // 处理新的聊天消息
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getNewChatMsg,
            this, &MainWindow::dealNewChatMsg);

    // 发送视频通话请求 C1->S
    connect(this, &MainWindow::requestVideoCall, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendVideoRequestMessage);

    // 处理视频通话请求 S->C2
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getVideoRequest,
            this, &MainWindow::dealVideoRequest);

    // 发送视频通话请求回复 C2->S
    connect(this, &MainWindow::respondVideoCall, &ClientMessageHandler::getInstance(),
            &ClientMessageHandler::sendVideoResponseMessge);

    // 处理视频通话请求结果 S->C1
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getVideoResponse,
            this, &MainWindow::dealVideoResponse);


    /* UI线程和DBService间通信 */
    // UI发信号告诉DBService更新好友关系
    connect(this, &MainWindow::sendNewFriendStatus, &DBService::getInstance(),
            &DBService::refreshNewFriendApplicationStatus);

    // DBService发信号告诉UI渲染好友申请
    connect(&DBService::getInstance(), &DBService::localNewFriendApplicationReady,
            this, &MainWindow::onLocalNewFriendApplicationReady);

    // DBService发信号告诉UI渲染好友关系
    connect(&DBService::getInstance(), &DBService::friendshipReady,
            this, &MainWindow::onFriendshipReady);

    // UI发信号，告诉DBService把新好友添加到数据库（向别人申请好友，别人同意了或者是同意别人的申请了）
    connect(this, &MainWindow::addNewFriendship,
            &DBService::getInstance(), &DBService::saveNewFriendship);

    // UI发信号，告诉DBService把聊天记录添加到数据库
    connect(this, &MainWindow::sendNewMessage,
            &DBService::getInstance(), &DBService::saveMeSendChatMsg);

    // UI发信号，向DBService请求本地聊天记录
    connect(this, &MainWindow::initChatMsgFromDBService,
            &DBService::getInstance(), &DBService::acquireChatMsg);

    // DBService发信号告诉UI好友聊天记录
    connect(&DBService::getInstance(), &DBService::friendChatMsgReady,
            this, &MainWindow::onFriendChatMsgReady);



    /* Handler线程和DBService间通信 */
    // Handler收到新好友申请，告诉DBService存到数据库
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getApplyFriendRequestToClient,
            &DBService::getInstance(), &DBService::saveNewFriendApplication);

    // Handler收到新聊天消息，告诉DBService存到数据库
    connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getNewChatMsg,
            &DBService::getInstance(), &DBService::saveFriendSendChatMsg);

    // Handler收到来自其他用户的好友审核结果
    // connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getApplyFriendResponseToClient,
    //         &DBService::getInstance(), &DBService::refreshFriendshipApplicationFromOther);



    // qDebug() << "连接是否成功:" << isConnected;
    // connect(&ClientMessageHandler::getInstance(), &ClientMessageHandler::getApplyFriendRequestToClient, this, [=](const QString receiverId, const QString applicantId,
    //                                                                                                               const QString nickname, const QString verifyInfo, const QDateTime applyTime){
    //     qDebug() << "main匿名函数执行成功";
    // });
}

// 点击最小化窗口
void MainWindow::onBtnSetMinClicked()
{
    this->showMinimized();
}

// 点击最大化窗口
void MainWindow::onBtnSetMaxClicked()
{
    if (this->isMaximized()) {
        this->showNormal(); // 如果已经最大化，点击后还原
        ui->btnSetMax->setText("最大化");
    } else {
        this->showMaximized(); // 如果未最大化，点击后最大化
        ui->btnSetMax->setText("恢复");
    }
}

// 点击关闭窗口按钮
void MainWindow::onBtnCloseClicked()
{
    this->close();
}

// 点击视频通话按钮
void MainWindow::onBtnVideoCallclicked()
{
    qDebug() << m_isVideo;
    if (m_isVideo)
    {
        // 处于通话状态让窗口
        m_videoCallWidget->raise();
        m_videoCallWidget->activateWindow();
        return;
    }
    // 通过Handler, 发送请求视频通话消息
    QString ipv4 = NetworkManager::getLocalIPv4();
    qDebug() << ipv4;
    if (ipv4.isEmpty())
    {
        // QMessageBox::warning(this, tr("网络异常"), tr("网卡检测失败"));
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setWindowTitle(tr("网络异常"));
        msgBox.setText(tr(("网卡检测失败")));

        // 设置字体颜色为白色
        msgBox.setStyleSheet(R"(
            QLabel { color: white; }
            QPushButton { color: white; background-color: #444444; }
            QMessageBox { background-color: #222222; }
        )");
        msgBox.exec();
        return;
    }
    emit requestVideoCall(m_userId, ipv4, m_curContact->getFriendId());
    m_videoCallWidget = new VideoCallWidget();
    m_videoCallWidget->show();
    m_isVideo = true;
    m_curVideoFriendId = m_curContact->getFriendId();
    // 视频通话窗口关闭，销毁窗口并重置状态
    connect(m_videoCallWidget, &VideoCallWidget::widgetClose, this, [this](){
        qDebug() << "call video widget close";
        this->m_isVideo = false;
        this->m_curVideoFriendId = QString();
        this->m_videoCallWidget->deleteLater();
    });

}

// 点击展示好友聊天视图（视图1）按钮
void MainWindow::onBtnShowChatViewClicked()
{
    // 视图2内容收起
    m_addFriendWidget->hide();
    m_applyFriendWidget->hide();
    // 视图3内容收起
    m_newFriendList->hide();
    m_showFriendApplicationWidget->hide();
    // 视图1内容展示
    m_contactListWidget->show();

}

// 点击展示添加、申请好友视图（视图2）按钮
void MainWindow::onBtnShowAddFriendViewClicked()
{
    // 视图1内容收起
    m_contactListWidget->hide();
    m_chatWidget->hide();
    // 视图3内容收起
    m_newFriendList->hide();
    m_showFriendApplicationWidget->hide();
    // 视图2内容展示
    m_addFriendWidget->show();
}

// 点击展示好友申请列表视图（视图3）按钮
void MainWindow::onBtnShowFriendApplicationsViewBtnClicked()
{
    // 视图1内容收起
    m_contactListWidget->hide();
    m_chatWidget->hide();
    // 视图2内容收起
    m_addFriendWidget->hide();
    m_applyFriendWidget->hide();
    // 视图3内容展示
    m_newFriendList->show();
}

// 点击某个联系人，展开右边聊天窗口
void MainWindow::onContactListItemClicked(QListWidgetItem *item)
{
    m_curContact = qobject_cast<ContactWidget*>(item->listWidget()->itemWidget(item));
    if (!m_curContact)
    {
        qDebug() << "联系人列表项转换失败";
        return;
    }
    m_chatWidget->getLabelFriendName()->setText(m_curContact->getAlias());
    // 切换联系人需要清空聊天窗
    m_chatWidget->getChatBox()->clear();
    // 渲染当前联系人的聊天记录
    emit initChatMsgFromDBService(m_curContact->getFriendId());
    m_chatWidget->show();
}

// 点击发送按钮，发送消息
void MainWindow::onBtnSendMsgClicked()
{
    // 获取用户输入消息
    QTextEdit* inputBox = m_chatWidget->getChatInputBox();
    QString msg = inputBox->toPlainText();
    if (msg == "")
    {
        return;
    }
    // 获取当前时间
    QString time = QDateTime::currentDateTime().toString(Qt::ISODate);


    ChatBox* chatBox = m_chatWidget->getChatBox();
    qDebug()<<"addMessage" << msg << time << chatBox->count();
    chatBox->insertNewChatMessage(msg, time, true);
    inputBox->clear();

    // 保存消息到本地数据库
    emit sendNewMessage(m_userId , m_curContact->getFriendId(), msg, QDateTime::currentDateTime());

}

// 点击查看新好友申请按钮（视图3）
void MainWindow::showNewFriendDetail()
{
    QObject *obj = sender();    // 获取信号的发出者
    QPushButton* checkBtn = qobject_cast<QPushButton*>(obj);    // 转换为QPushButton
    if (!checkBtn)
    {
        // 转换失败
        return;
    }
    QWidget *parentWidget = checkBtn->parentWidget(); // 获取父控件
    NewFriendWidget* newFriendWidget = qobject_cast<NewFriendWidget*>(parentWidget);
    if (!newFriendWidget) {
        // 转换失败
        return;
    }
    // 设置当前窗口对应的左边小项
    curNewFriendWidget = newFriendWidget;
    // 获取好友申请窗口成功，渲染验证窗口
    m_showFriendApplicationWidget->setId(newFriendWidget->getId());
    m_showFriendApplicationWidget->show();
    m_showFriendApplicationWidget->getShowIdLabel()->setText(newFriendWidget->getFriendId());
    m_showFriendApplicationWidget->getShowNicknameLabel()->setText(newFriendWidget->getNickname());
    m_showFriendApplicationWidget->getShowVerifyInfoLabel()->setText(newFriendWidget->getVerifyInfo());
    // 设置默认备注为昵称
    m_showFriendApplicationWidget->getAliasLineEdit()->setText(newFriendWidget->getNickname());

}

// 点击同意好友申请按钮
void MainWindow::onAcceptedBtnClicked()
{
    QString friendId = m_showFriendApplicationWidget->getShowIdLabel()->text();
    QString alias = m_showFriendApplicationWidget->getAliasLineEdit()->text();
    int id = m_showFriendApplicationWidget->getId();
    FriendVerifyStatus status = FriendVerifyStatus::Accpeted;
    // 通知Handler线程打包，同时DBService更新本地数据库好友申请
    emit sendNewFriendStatus(status, alias, id);
    // 同时更新好友关系（因为是同意）
    QString nickname = m_showFriendApplicationWidget->getShowNicknameLabel()->text();
    emit addNewFriendship(friendId, nickname, alias, QDateTime::currentDateTime());
    // 更新左边栏
    updateNewFriendApplicationList(friendId);
}

// 点击拒绝好友申请按钮
void MainWindow::onRejectedBtnClicked()
{
    QString friendId = m_showFriendApplicationWidget->getShowIdLabel()->text();
    int id = m_showFriendApplicationWidget->getId();
    FriendVerifyStatus status = FriendVerifyStatus::Rejected;
    // 通知Handler线程打包，同时DBService更新本地数据库
    emit sendNewFriendStatus(status, "", id);
    updateNewFriendApplicationList(friendId);
}

// 更新待审核好友列表
void MainWindow::updateNewFriendApplicationList(const QString friendId)
{
    // 获取待审核好友列表中的所有NewFriendWidget控件
    for (int i = 0; i < m_newFriendList->count(); ++i) {
        // 获取每个QListWidgetItem
        QListWidgetItem *item = m_newFriendList->item(i);
        // 获取与QListWidgetItem关联的QWidget
        QWidget *widget = m_newFriendList->itemWidget(item);
        NewFriendWidget* newFriendWidget = qobject_cast<NewFriendWidget*>(widget);
        if (!newFriendWidget)
        {
            // 转换失败
            continue;
        }
        if (newFriendWidget->getFriendId() == friendId)
        {
            newFriendWidget->getBtnCheck()->setText(tr("已完成"));
            newFriendWidget->getBtnCheck()->setEnabled(false);
        }
        // qDebug() << "Widget for item" << i << ":" << widget;
    }
}

// 点击登出按钮
void MainWindow::onBtnLogoutClicked()
{
    // 让MessageHandler告诉服务器登出
    emit sendLogoutInfo(m_userId);

}

// 点击搜索新用户按钮
void MainWindow::onSearchNewUserBtnClicked()
{
    emit sendSearchNewUserInfo(m_addFriendWidget->getNewUserIdEditLine()->text());
}

// 点击添加好友（把好友信息展示到右边大屏）按钮
void MainWindow::onCheckFriendInfoBtnClicked()
{
    QString userId = m_addFriendWidget->getUserIdLabel()->text();
    QString nickname = m_addFriendWidget->getNicknameLabel()->text();
    m_applyFriendWidget->getUserIdShow()->setText(userId);
    m_applyFriendWidget->getNicknameShow()->setText(nickname);
    m_applyFriendWidget->show();
}

// 点击提交申请（好友）按钮
void MainWindow::onApplyFriendBtnClicked()
{
    QString userId = m_userId;
    QString friendId = m_applyFriendWidget->getUserIdShow()->text();
    QString alias = m_applyFriendWidget->getInputAlias()->text();
    QString verifyInfo = m_applyFriendWidget->getInputVerifiedInfo()->text();
    emit sendApplyFriendInfo(userId, friendId, alias, verifyInfo);
}

// 收到Handler的登出请求进行登出操作
void MainWindow::dealLogoutResponseMessage(const QString status, const QString reason)
{
    // 返回到登录界面
    if (status == JsonValue::STATUS_SUCCESS)
    {
        emit backLoginWidget(this);
    }
    else
    {
        QMessageBox::warning(this, tr("登出失败"), tr("未知错误"));
    }
}

// 收到Handler的搜索结果进行搜索结果显示
void MainWindow::dealSearchUserResponseMessage(const QString status, const QString reason, const QString userId, const QString nickname)
{
    if (status == JsonValue::STATUS_SUCCESS)
    {
        m_addFriendWidget->getUserIdLabel()->setText(userId);
        m_addFriendWidget->getNicknameLabel()->setText(nickname);
        m_addFriendWidget->getResultWidget()->show();
    }
    else
    {
        m_addFriendWidget->getResultWidget()->hide();
    }
}

// 收到Handler的好友申请请求进行展示
void MainWindow::dealApplyFriendRequestMessageToClient(const QString receiverId, const QString applicantId,
    const QString nickname, const QString verifyInfo, const QDateTime applyTime, const int id)
{
    qDebug() << "得到好友申请信号";
    // 未知错误（收到了别人的好友请求）
    if (receiverId != m_userId)
    {
        qDebug() << "error: 收到了别人的";
        return;
    }
    qDebug() << "插入新的好友申请";
    QListWidgetItem* item = new QListWidgetItem;
    item->setSizeHint(QSize(200,80));
    NewFriendWidget* newFriend = new NewFriendWidget(applicantId, nickname, verifyInfo, applyTime, id, nickname, FriendVerifyStatus::Unverified);
    m_newFriendList->addItem(item);
    m_newFriendList->setItemWidget(item, newFriend);
    connect(newFriend->getBtnCheck(), &QPushButton::clicked, this, &MainWindow::showNewFriendDetail);

}

// 收到Handler的好友申请审核结果
void MainWindow::dealNewFriendApplicationResult(const QString friendId, const QString nickname,
                const QString status, const QString alias, const QDateTime resultTime)
{
    qDebug() << "得到好友申请审核结果";
    if (status == JsonValue::STATUS_REJECTED)
    {
        qDebug() << "新好友未通过申请";
        return;
    }
    qDebug() << "新好友来喽";
    QListWidget* listContact = m_contactListWidget->getListContact();
    QListWidgetItem* item = new QListWidgetItem;
    item->setSizeHint(QSize(200,80));
    ContactWidget* contactItem = new ContactWidget(friendId, nickname, alias, resultTime);
    listContact->addItem(item);
    listContact->setItemWidget(item, contactItem);
    // 发信号通知本地数据库
    emit addNewFriendship(friendId, nickname, alias, resultTime);
}

// 收到Handler的好友聊天消息
void MainWindow::dealNewChatMsg(const QString friendId, const QString msg, const QDateTime sendTime)
{
    // 1.首先判断是否需要渲染，如果当前聊天框不是这个用户就不需要渲染
    if (!m_curContact || m_curContact->getFriendId() != friendId)
    {
        qDebug() << "未展示不渲染";
        return;
    }
    // 获取当前时间
    QString time = sendTime.toString(Qt::ISODate);
    ChatBox* chatBox = m_chatWidget->getChatBox();
    chatBox->insertNewChatMessage(msg, time, false);
    // qDebug()<<"addMessage" << msg << time << chatBox->count();
}

// 收到Handler的视频通话请求
void MainWindow::dealVideoRequest(const QString requestUserId, const QString requestUserIp)
{
    // 1. 判断当前用户是否在视频通话中
    if (m_isVideo)
    {
        // 当前正在视频通话中，无法和新请求者通话
        emit respondVideoCall(m_userId, requestUserId, JsonValue::STATUS_BUSY, "");
        return;
    }
    // 2. 让当前用户选择是否接受视频通话请求
    m_videoTipWidget = new VideoCallTipWidget();
    // 这里也可以读本地数据库获取显示昵称什么的
    m_videoTipWidget->getUserTip()->setText(requestUserId + "向您发起通话请求");
    m_videoTipWidget->show();
    connect(m_videoTipWidget->getAgreeBtn(), &QPushButton::clicked, this, [=](){
        // 同意后获取ip,发消息关闭窗口
        QString status = JsonValue::STATUS_ACCEPTED;
        QString ipv4 = NetworkManager::getLocalIPv4();
        qDebug() << "发给对方我的ipv4:" << ipv4;
        if (ipv4.isEmpty())
        {
            status = JsonValue::STATUS_NETWORK_ERROR;
        }
        emit respondVideoCall(m_userId, requestUserId, status, ipv4);
        m_videoTipWidget->close();
        // 打开视频通话窗口
        m_videoCallWidget = new VideoCallWidget();
        m_videoCallWidget->show();
        m_videoCallWidget->setFriendIp(m_userId, requestUserId, requestUserIp);
        m_isVideo = true;
        m_curVideoFriendId = requestUserId;

        // 视频通话窗口关闭，销毁窗口并重置状态
        connect(m_videoCallWidget, &VideoCallWidget::widgetClose, this, [this](){
            // qDebug() << "call video widget close";
            this->m_isVideo = false;
            this->m_curVideoFriendId = QString();
            this->m_videoCallWidget->deleteLater();
        });
    });
    connect(m_videoTipWidget->getRejectBtn(), &QPushButton::clicked, this, [=](){
        // 拒绝后发消息关窗口
        emit respondVideoCall(m_userId, requestUserId, JsonValue::STATUS_REJECTED, "");
        m_videoTipWidget->close();
    });
}

// 收到Handler的视频通话请求结果
void MainWindow::dealVideoResponse(const QString requestUserId,
    const QString responseUserId, const QString status, const QString responseUserIp)
{
    if (requestUserId != m_userId)
    {
        // 按理来说不应该出现不一致
        return;
    }
    // 1. 检测是不是最新请求视频的用户
    if (responseUserId != m_curVideoFriendId)
    {
        // 可能会发生用户一开始点了视频通话，但是对方还没同意，就取消了
        return;
    }
    // 2. 弹出提示窗口表示对方同意或拒绝
    if (status == JsonValue::STATUS_ACCEPTED)
    {
        // 对方同意视频通话
        m_videoCallWidget->setFriendIp(m_userId, responseUserId, responseUserIp);
        return;
    }
    // 执行到这里无法进行视频通话，需要关闭窗口并做出相应提示
    emit m_videoCallWidget->widgetClose();
    QString title = tr("视频通话失败");
    QString reason = tr("未知原因");
    if (status == JsonValue::STATUS_REJECTED)
    {
       reason = tr("对方已拒绝");
    }
    else if (status == JsonValue::STATUS_BUSY)
    {
        reason = tr("对方正忙");
    }
    else if (status == JsonValue::STATUS_OFFLINE)
    {
        reason = tr("对方不在线");
    }
    else if (status == JsonValue::STATUS_NETWORK_ERROR)
    {
        reason = tr("对方网络异常");
    }
    QMessageBox msgBox(this);
    msgBox.setIcon(QMessageBox::Warning);
    msgBox.setWindowTitle(title);
    msgBox.setText(reason);

    // 设置字体颜色为白色
    msgBox.setStyleSheet(R"(
            QLabel { color: white; }
            QPushButton { color: white; background-color: #444444; }
            QMessageBox { background-color: #222222; }
        )");
    msgBox.exec();
}


// 收到DBService的本地数据
void MainWindow::onLocalNewFriendApplicationReady(const QString friendId, const QString nickname,
                            const QString verifyInfo, const QDateTime applyTime, const int id,
                            const QString alias, const FriendVerifyStatus status)
{
    // 渲染到视图3左边窗口上
    NewFriendWidget* newFriend = new NewFriendWidget(friendId, nickname, verifyInfo, applyTime, id, alias, status);
    QListWidgetItem* item = new QListWidgetItem;
    item->setSizeHint(QSize(200,80));
    m_newFriendList->addItem(item);
    m_newFriendList->setItemWidget(item, newFriend);
    connect(newFriend->getBtnCheck(), &QPushButton::clicked, this, &MainWindow::showNewFriendDetail);
}

// 收到DBService的本地数据（好友关系）
void MainWindow::onFriendshipReady(const QString friendId, const QString nickname,
                       const QString alias, const QDateTime time)
{
    // 渲染到视图1左边窗口上
    QListWidget* listContact = m_contactListWidget->getListContact();
    QListWidgetItem* item = new QListWidgetItem;
    item->setSizeHint(QSize(200,80));
    ContactWidget* contactItem = new ContactWidget(friendId, nickname, alias, time);
    listContact->addItem(item);
    listContact->setItemWidget(item, contactItem);

}

// 收到DBService的本地数据（好友聊天记录）
void MainWindow::onFriendChatMsgReady(const QString friendId, const QString chatMsg,
                          const QDateTime datetime, const bool isMeSend)
{
    // if (m_curContact && m_curContact->getFriendId() == friendId)
    // {

    // }
    qDebug() << "加载本地数据库聊天消息";
    // 获取当前时间
    QString time =datetime.toString(Qt::ISODate);
    ChatBox* chatBox = m_chatWidget->getChatBox();
    chatBox->insertNewChatMessage(chatMsg, time, isMeSend);
    // qDebug()<<"addMessage" << msg << time << chatBox->count();
}

// 托盘激活
void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger) // 单击
    {
        // 双击托盘图标，恢复窗口正常大小
        this->showNormal();
        // 激活窗口，把焦点给当前窗口
        this->activateWindow();
    }
}

// protected:

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (m_trayIcon->isVisible()) {
        hide(); // 隐藏窗口
        event->ignore(); // 阻止窗口关闭
    }
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setPen(Qt::NoPen);  // 不显示边框
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);   // 开启平滑渲染更丝滑
    painter.setRenderHint(QPainter::Antialiasing, true);    // 开启抗锯齿更丝滑

    if (!m_backgroundCache.isNull()) {
        // 设置圆角矩形裁剪路径
        QPainterPath path;
        path.addRoundedRect(m_shadowWidth, m_shadowWidth, this->width() - 2 * m_shadowWidth, this->height() - 2 * m_shadowWidth, m_radius, m_radius);
        painter.setClipPath(path);  // 设置剪切区域
        // 将背景图片填充到窗口区域
        painter.drawPixmap(m_shadowWidth, m_shadowWidth, this->width() - 2 * m_shadowWidth, this->height() - 2 * m_shadowWidth, m_backgroundCache);
    }

    QPainter painter2(this);
    // 直接绘制缓存里的阴影边框
    painter2.drawPixmap(0, 0, m_shadowCache);

    QWidget::paintEvent(event);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    // 更新阴影边框的缓存
    m_shadowCache = QPixmap(this->size());  // 创建一个与窗口大小一致的透明图层
    m_shadowCache.fill(Qt::transparent);  // 填充透明色
    PaintShadow sp(&m_shadowCache, m_shadowWidth, m_radius);

    // 更新背景图片的缓存
    m_backgroundCache = QPixmap(":/images/mainBackground.jpg");

    // 调整右上角窗口设置按钮
    int x_close = this->width() - ui->btnClose->width() - m_shadowWidth;
    int x_setMax = x_close - ui->btnSetMax->width();
    int x_setMin = x_setMax - ui->btnSetMin->width();
    ui->btnClose->setGeometry(QRect(x_close, m_shadowWidth, ui->btnClose->width(), ui->btnClose->height()));
    ui->btnSetMax->setGeometry(QRect(x_setMax, m_shadowWidth, ui->btnSetMax->width(), ui->btnSetMax->height()));
    ui->btnSetMin->setGeometry(QRect(x_setMin, m_shadowWidth, ui->btnSetMin->width(), ui->btnSetMin->height()));

    // 打印按钮位置
    // qDebug() << "Window size:" << this->geometry();
    // qDebug() << "btnClose geometry:" << ui->btnClose->geometry();
    // qDebug() << "btnSetMax geometry:" << ui->btnSetMax->geometry();
    // qDebug() << "btnSetMin geometry:" << ui->btnSetMin->geometry();

    int sideLength = 40;
    // 左边距
    int xOffset = 30;
    // 上边距
    int yOffset = 90;
    // 按钮垂直间隔
    int y_step = 60;
    int mainWindowSplitterX = 2 * xOffset - m_shadowWidth + sideLength;
    int mainWindowSplitterY = m_shadowWidth;
    int mainWindowSplitterWidth = this->width() - mainWindowSplitterX - m_shadowWidth;
    int mainWindowSplitterHeight = this->height() - m_shadowWidth * 2;
    ui->mainWindowSplitter->setGeometry(
        QRect(mainWindowSplitterX, mainWindowSplitterY, mainWindowSplitterWidth, mainWindowSplitterHeight));
    // 触发一下分割条来初始化
    emit ui->mainWindowSplitter->splitterMoved(0,0);
    // 重置登出按钮大小位置
    int btnLogoutY = this->height() - sideLength - xOffset;
    ui->btnLogOut->move(xOffset, btnLogoutY);
    QWidget::resizeEvent(event);
}

